//1.渲染整个学生列表
const getStudentsMessage = async () => {
  const { data } = await get('/students')
  const studentHTML = data
    .map(item => {
      return `
      <tr>
        <td>${item.name}</td>
        <td>${item.age}</td>
        <td>${item.gender === 1 ? '男' : '女'}</td>
        <td>第${item.group}组</td>
        <td>${item.hope_salary}</td>
        <td>${item.salary}</td>
        <td>${item.province} ${item.city} ${item.area}</td>
        <td>
          <a href="javascript:;" class="text-success mr-3"><i data-id=${
            item.id
          } class="bi bi-pen"></i></a>
          <a href="javascript:;" class="text-danger"><i data-id=${
            item.id
          } class="bi bi-trash"></i></a>
        </td>
      </tr>
    `
    })
    .join('')
  document.querySelector('.list').innerHTML = studentHTML
  document.querySelector('.total').innerHTML = data.length
}
getStudentsMessage()

// 初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)
const ps = document.querySelector('[name=province]')
const cs = document.querySelector('[name=city]')
const as = document.querySelector('[name=area]')
const form = document.querySelector('#form')

// modal.show()
//2.获取省，市，区的信息导入到真实dom中
const initCity = async () => {
  const provinceRes = await get('/api/province')

  // console.log(provinceRes);

  const provinceHTML = provinceRes.data
    .map(item => `<option value="${item}">--${item}--</option>`)
    .join('')

  ps.innerHTML = '<option value="北京">--省份--</option>' + provinceHTML

  ps.addEventListener('change', async function () {
    cs.value = ''
    renderCity(ps.value)

    cs.addEventListener('change', async function () {
      as.value = ''
      renderArea(ps.value, cs.value)
    })
  })
}

initCity()

const renderCity = async pname => {
  const cityRes = await get('/api/city', { pname })

  const cityHTML = cityRes.data.map(item => `<option value="${item}">--${item}--</option>`).join('')

  cs.innerHTML = '<option value="北京">--城市--</option>' + cityHTML
}

const renderArea = async (pname, cname) => {
  const areaRes = await get('/api/area', { pname, cname })

  const areaHTML = areaRes.data.map(item => `<option value="${item}">--${item}--</option>`).join('')

  as.innerHTML = '<option value="丰台区">--地区--</option>' + areaHTML
}

//3.点击添加按钮显示modal层
document.querySelector('#openModal').addEventListener('click', function () {
  form.reset()
  modalBox.dataset.id = 'add'
  modal.show()
})

//4.给确定按钮绑定点击事件，但是分为两种情况，新增和修改，通过自定义属性判断
document.querySelector('#submit').addEventListener('click', async function () {
  const data = serialize(form, { hash: true })

  console.log(data)
  data.age = +data.age
  data.hope_salary = +data.hope_salary
  data.salary = +data.salary
  data.gender = +data.gender
  data.group = +data.group

  if (modalBox.dataset.id === 'add') {
    try {
      const res = await post('/students', data)
      modal.hide()
      alert('添加成功')
      getStudentsMessage()
    } catch (error) {
      alert('添加失败')
    }
  } else {
    // console.log(modalBox.dataset.id);
    try {
      const res = await axios({ method: 'put', url: '/students/' + modalBox.dataset.id, data })
      modal.hide()
      alert('修改成功')
      getStudentsMessage()
    } catch (error) {
      alert('修改失败')
    }
  }
})

//5.事件委托的形式，绑定修改和删除事件，通过类名判断
//事件委托
document.querySelector('.list').addEventListener('click', async function (e) {
  const btn = e.target
  if (btn.classList.contains('bi-pen')) {
    // console.log(btn.dataset.id);
    const studentMessage = await get('/students/' + btn.dataset.id)

    document.querySelector('[name=name').value = studentMessage.data.name
    studentMessage.data.gender
      ? (document.querySelector('#cb01').checked = true)
      : (document.querySelector('#cb02').checked = true)
    document.querySelector('[name=age').value = studentMessage.data.age
    document.querySelector('[name=group').value = studentMessage.data.group
    document.querySelector('[name=hope_salary').value = studentMessage.data.hope_salary
    document.querySelector('[name=salary').value = studentMessage.data.salary

    ps.value = studentMessage.data.province

    await renderCity(ps.value)

    cs.value = studentMessage.data.city

    await renderArea(ps.value, cs.value)

    as.value = studentMessage.data.area

    modalBox.dataset.id = btn.dataset.id

    modal.show()
  } else if (btn.classList.contains('bi-trash')) {
    console.log(btn.dataset.id)
    try {
      await axios({ method: 'DELETE', url: '/students/' + btn.dataset.id })
      getStudentsMessage()
      alert('删除成功')
    } catch (error) {
      alert('删除失败')
    }
  }
})
